package com.mspbots.rule.exceptions.cw;

import cn.hutool.core.util.StrUtil;
import com.mspbots.cw.request.TenantTimeEntryDTO;
import lombok.extern.slf4j.Slf4j;
import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Fact;
import org.jeasy.rules.annotation.Rule;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Dinnes Zhang
 * @date 12:32 2019/10/28
 **/
@Slf4j
@Rule(name = "RemoteSupportAfterTravel", description = "RemoteSupportAfterTravel")
public class RemoteSupportAfterTravel extends CwBaseRule implements IcwBaseRule {

    @Condition
    @Override
    public boolean condition(@Fact(FACT) TenantTimeEntryDTO entry) {
        try {
            if (!setUserMapping(entry.getTenantUserId()) || super.checkMessage(entry)) {
                return false;
            }

            if ("onsite".equalsIgnoreCase(entry.getExtend().findPath("workType").get("name").asText())) {
                return false;
            }
            Map<String, Object> params = Map.of("tenantId", entry.getTenantId(),
                    "cwUid", entry.getCwUid(), "enteredDate", entry.getEnteredDate());
            TenantTimeEntryDTO tenantTimeEntryDTO = this.coreClient.get("/tenant/user-time-entry/findLastOneById", params, TenantTimeEntryDTO.class).block();
            if (!StringUtils.isEmpty(tenantTimeEntryDTO) && "travel".equalsIgnoreCase(tenantTimeEntryDTO.getExtend().findPath("workType").get("name").asText())) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("RemoteSupportAfterTravel rule execute error [{}] : {}", e.getStackTrace()[0].getLineNumber(), e.getMessage());
        }
        return false;
    }

    @Action
    @Override
    public void action(@Fact(FACT) TenantTimeEntryDTO entry) {
        Map<String, Object> param = Map.of("tenantId", entry.getTenantId(),
                "cwUid", entry.getCwUid(), "enteredDate", entry.getEnteredDate());
        TenantTimeEntryDTO tenantTimeEntryDTO = this.coreClient.get("/tenant/user-time-entry/findLastOneById", param, TenantTimeEntryDTO.class).block();
        String msg = buildMessage(entry.getEnteredDate());
        Map<String, Object> params = new HashMap<>();
        params.put("TimeEntryLink1", suffixCwLink(entry.getCwTid()));
        params.put("TYPE", entry.getExtend().findPath("workType").get("name").asText());
        params.put("TimeEntryLink2", suffixCwLink(tenantTimeEntryDTO.getCwTid()));
        String message = StrUtil.format(msg, params);
        messages.setMessage(message);
        messages.setBusinessId(entry.getCwTid());
        insertMessage();
    }
}
